package service

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"goEmqxToDb/config"
	"goEmqxToDb/handler"
	"goEmqxToDb/mqtt"

	"github.com/sevlyar/go-daemon"
)

// RunAsDaemon 在Linux下以后台服务方式运行
func RunAsDaemon() {
	cntxt := &daemon.Context{
		PidFileName: "goemqxtodb.pid",
		PidFilePerm: 0644,
		LogFileName: "goemqxtodb.log",
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
		Args:        []string{"[goemqxtodb-daemon]"},
	}

	d, err := cntxt.Reborn()
	if err != nil {
		fmt.Println("Unable to run: ", err)
		os.Exit(1)
	}
	if d != nil {
		return
	}
	defer cntxt.Release()

	log.Println("Daemon started")
	Run()
}

// Run 主业务逻辑
func Run() {
	log.Println("GoEmqxToDb service started")

	// 加载配置
	configs, err := config.LoadConfig("config/setting.json")
	if err != nil {
		log.Fatalf("加载配置失败: %v", err)
	}

	if len(configs) == 0 {
		log.Fatal("配置文件中没有找到有效配置")
	}

	// 创建MQTT客户端
	mqttClient, err := mqtt.NewClient()
	if err != nil {
		log.Fatalf("创建MQTT客户端失败: %v", err)
	}

	// 连接到MQTT服务器
	err = mqttClient.Connect()
	if err != nil {
		log.Fatalf("连接MQTT服务器失败: %v", err)
	}
	defer mqttClient.Disconnect()

	// 创建消息处理器
	messageHandler := handler.NewMessageHandler(mqttClient)
	defer messageHandler.Close()

	// 订阅主题
	err = mqttClient.Subscribe(messageHandler.HandleMessage)
	if err != nil {
		log.Fatalf("订阅主题失败: %v", err)
	}

	log.Println("MQTT订阅成功，等待消息...")

	// 设置信号处理
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// 等待退出信号
	<-sigChan
	log.Println("Shutting down GoEmqxToDb service...")
}

// mainLoop 主业务循环（保留用于兼容性）
func mainLoop() {
	ticker := time.NewTicker(30 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			log.Println("GoEmqxToDb is running...")
		}
	}
}
